/**
 * Copyright 2010 Mark Wyszomierski
 */
package com.joelapenna.foursquared.widget;

import android.content.res.Resources;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Takes an EditText and a TextView, and as the user types in the EditText, updates
 * the TextView with the number of characters left until maxLength is reached.
 * 
 * Unfortunately we can't find out the max length from the EditText itself, or from
 * a possible InputFilter.LengthFilter applied to it. We take the maxLength value
 * from the user and trust that's really the max that was set.
 * 
 * @date October 11, 2010
 * @author Mark Wyszomierski (markww@gmail.com)
 */
public class CharactersLeft {
    
    /**
     * @param resources From context.getResources().
     * @param source The EditText to bind to.
     * @param target The TextView to update whenever the user types in the EditText.
     * @param sentence The string resource ID to use for the TextView, should have two %d
     *                 in it, the first for # characters typed, the second for the max length.
     * @param maxLength The max number of characters the EditText will accept.
     */
    public static void bind(final Resources resources, 
                            final EditText source, 
                            final TextView target, 
                            final int sentence, 
                            final int maxLength) {
        source.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                target.setText(resources.getString(sentence, s.length(), maxLength));
            }
        });
        target.setText(resources.getString(sentence, 0, maxLength));
    }
}
